package com.ftdigital.primemovers_operators;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;

import com.bugtags.library.Bugtags;
import com.ftdigital.primemovers_operators.config.GlobalData;
import com.ftdigital.primemovers_operators.fragment.HistoryFragment;
import com.ftdigital.primemovers_operators.fragment.HomeFragment_;
import com.ftdigital.primemovers_operators.fragment.InfoEnsureFragment_;
import com.ftdigital.primemovers_operators.fragment.SettingFragment_;
import com.ftdigital.primemovers_operators.fragment.HistoryFragment_;
import com.ftdigital.primemovers_operators.model.AddDetail;
import com.ftdigital.primemovers_operators.model.AddOilInfo;
import com.ftdigital.primemovers_operators.util.loading.Loading;
import com.readystatesoftware.systembartint.SystemBarTintManager;


public class MainActivity extends FragmentActivity {

    private static MainActivity mainActivity;
    private static FragmentManager fragmentManager;
    public LayoutInflater layoutInflater;
    public final static int FILECHOOSER_RESULTCODE = 1;
    public ValueCallback<Uri> mUploadMessage;

    //定义数组来存放Fragment界面
    private Class fragmentArray[] = {HomeFragment_.class, HistoryFragment_.class,
            SettingFragment_.class};

    //定义数组来存放按钮图片
    private int mImageViewArray[] = {R.drawable.tab_home_btn, R.drawable.tab_history_btn,
            R.drawable.tab_setting_btn};


    //Tab选项卡的文字
    private String mTextviewArray[] = {"个人主页", "加油历史", "我的设置"};

    public static MainActivity getInstance() {
        return mainActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucentStatus();
        setContentView(R.layout.activity_main);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        GlobalData.screenWidth = dm.widthPixels;
        GlobalData.screenHeight = dm.heightPixels;
//        Log.i(GlobalData.TAG, "screenWidth:"+GlobalData.screenWidth);
//        Log.i(GlobalData.TAG, "screenHeight:"+GlobalData.screenHeight);
        mainActivity = this;
        Loading.context = this;
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 解决键盘顶tab问题
        fragmentManager = getSupportFragmentManager();
        layoutInflater = LayoutInflater.from(this);
        intiTab();

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    }
    /**
     * 设置状态栏背景状态
     */
    private void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        // enable status bar tint
        tintManager.setStatusBarTintEnabled(true);
        // enable navigation bar tint
        tintManager.setNavigationBarTintEnabled(true);
        // set a custom tint color for all system bars
        tintManager.setTintColor(Color.parseColor("#09ff8b0a"));
    }
    public static FragmentTabHost tabHost;

    private void intiTab() {
        tabHost = (FragmentTabHost) findViewById(R.id.tab);
        tabHost.setup(this, getSupportFragmentManager(), R.id.content);
        if (android.os.Build.VERSION.SDK_INT > 10) {
            tabHost.getTabWidget().setShowDividers(0);
        }
        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            tabHost.addTab(tabSpec, fragmentArray[i], null);
        }
        if (Build.VERSION.SDK_INT > 10) {
//            tabHost.getTabWidget().setShowDividers(10);
            tabHost.getTabWidget().setDividerPadding(0);
        }
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private ImageView imageview;

    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);
        imageview = (ImageView) view.findViewById(R.id.imageview);
        imageview.setImageResource(mImageViewArray[index]);
        return view;
    }


    private boolean is2CallBack = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (fragmentManager.getBackStackEntryCount() != 0) {
                if (fragmentManager.getBackStackEntryCount() == 1&&tabHost.getCurrentTab() ==1) {
                    tabHost.setCurrentTab(0);
                    tabHost.setCurrentTab(1);
                }
//                String name = fragmentManager.getBackStackEntryAt(
//                        fragmentManager.getBackStackEntryCount() - 1).getName();
                fragmentManager.popBackStack();
            } else {
                if (!is2CallBack) {
                    is2CallBack = true;
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            is2CallBack = false;
                        }
                    }, 1500);
                } else {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        }
        return true;
    }
    /**
     * @param from       当前fragment
     * @param toFragment 跳转到的fragment
     */
    public void switchFragment(Fragment from, Fragment toFragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .hide(from).replace(R.id.content_none_bottom, toFragment).addToBackStack(null).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注：回调 1
        Bugtags.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注：回调 2
        Bugtags.onPause(this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        Bugtags.onDispatchTouchEvent(this, event);
        return super.dispatchTouchEvent(event);
    }
    private final static int SCANNIN_GREQUEST_CODE = 1;


}
